import { createStore } from "redux";

let userInfo = localStorage.getItem("userInfo");
try {
    userInfo = JSON.parse(userInfo) || {};
} catch (err) {
    userInfo = {};
}

const initState = {
    userInfo,
};

const reducer = (state, { type, payload }) => {
    let newState = { ...state };
    switch (type) {
        case "login":
            newState.userInfo = payload;
            localStorage.setItem("userInfo", JSON.stringify(payload));
            return newState;
        case "logout":
            newState.userInfo = {};
            localStorage.removeItem("userInfo");
            return newState;

        default:
            return newState;
    }
};

const store = createStore(reducer, initState);

export default store;
